package com.real.fact.web.customer.application;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

import com.globant.katari.core.application.ValidatableCommand;
import com.real.fact.web.customer.domain.Customer;
import com.real.fact.web.customer.domain.CustomerRepository;

public class SaveCustomerCommand implements ValidatableCommand<Void> {

  private final CustomerRepository customerRepository;
  private long customerId;
  private String name;
  private String cuil;
  private String address;
  private String phone;
  private String city;
  private String contactInfo;

  public SaveCustomerCommand(final CustomerRepository customerRepository) {
    this.customerRepository = customerRepository;
  }

  public void init() {
    if (customerId > 0) {
      Customer customer = customerRepository.findById(customerId);
      name = customer.getName();
      address = customer.getAddress();
      phone = customer.getPhone();
      cuil = customer.getCuil();
      city = customer.getCity();
      contactInfo = customer.getContactInfo();
    }
  }

  public Void execute() {
    Customer customer = null;
    if (customerId > 0) {
      customer = customerRepository.findById(customerId);
      customer.modify(name, cuil, address, city, phone, contactInfo);
    } else {
      customer = new Customer(name, cuil, address, city, phone, contactInfo);
    }
    customerRepository.save(customer);
    return null;
  }

  public String getCity() {
    return city;
  }

  public void setCity(final String city) {
    this.city = city;
  }

  public String getContactInfo() {
    return contactInfo;
  }

  public void setContactInfo(final String contactInfo) {
    this.contactInfo = contactInfo;
  }

  public long getCustomerId() {
    return customerId;
  }

  public void setCustomerId(final long customerId) {
    this.customerId = customerId;
  }

  public String getName() {
    return name;
  }

  public void setName(final String name) {
    this.name = name;
  }

  public String getCuil() {
    return cuil;
  }

  public void setCuil(final String cuil) {
    this.cuil = cuil;
  }

  public String getAddress() {
    return address;
  }

  public void setAddress(final String address) {
    this.address = address;
  }

  public String getPhone() {
    return phone;
  }

  public void setPhone(final String phone) {
    this.phone = phone;
  }

  public CustomerRepository getCustomerRepository() {
    return customerRepository;
  }

  public void validate(final Errors errors) {
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "Name is empty");
  }

}
